package com.ice.framework.web.config;

import cn.hutool.core.collection.CollectionUtil;
import com.ice.framework.web.handler.AutoResultReturnValueHandler;
import com.ice.framework.web.listener.UserInfoContextListener;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * 将AutoResultReturnValueHandler注入到SpringMvc框架中
 * @author wangwei
 * @Date 2021/12/23 09:53
 */
@Configuration
public class ReturnValueHandlerConfig {

    /**
     * 將自定义AutoResultReturnValueHandler添加
     * @Author wangwei
     * @Date 2021/12/23
     */
    @Bean
    @ConditionalOnMissingBean({AutoResultReturnValueHandler.class})
    public AutoResultReturnValueHandler handlerAutoResultReturn(RequestMappingHandlerAdapter requestMappingHandlerAdapter) {
        AutoResultReturnValueHandler handler = new AutoResultReturnValueHandler();
        List<HandlerMethodReturnValueHandler> list = new ArrayList<>();
        list.add(handler);
        if (CollectionUtil.isNotEmpty(requestMappingHandlerAdapter.getReturnValueHandlers())) {
            list.addAll(requestMappingHandlerAdapter.getReturnValueHandlers());
        }
        requestMappingHandlerAdapter.setReturnValueHandlers(list);
        return handler;
    }
    
    /**
     * 拦截所有servlet请求，并写入用户
     * @Author wangwei
     * @Date 2024/5/11
     */
    @Bean
    public UserInfoContextListener UserInfoContextListener() {
        return new UserInfoContextListener();
    }
}
